package com.ruitaowang.core.web;

import com.alibaba.fastjson.JSON;
import com.ruitaowang.core.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Controller层父类，包括一些常用的方法
 */
public abstract class BaseController {

    public static final String AUTHUSER = "authuser";
    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    protected String renderJson(Object object){
        return JSON.toJSONString(object);
    }

    protected String renderText(Object object){
        return object.toString();
    }

    protected HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return servletRequestAttributes.getRequest();
    }
    protected HttpSession getSession(){
        return getRequest().getSession();
    }

    protected void setSessionAttribute(String k, Object v){
        LOGGER.info("session",k,v);
        getSession().setAttribute(k, v);
    }

    protected Object getSessionAttribute(String k){
        return getSession().getAttribute(k);
    }

    protected HttpServletResponse getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }
//    protected SysUser currentUser(){
//
//        return (SysUser) getSessionAttribute(AUTHUSER);
//    }

    protected void setUser(SysUser user){
        setSessionAttribute(AUTHUSER, user);
    }
}